<template>
	<view class="register_content flexC-FS-C">
		<image class="logoIcon" :src="imagesYqgjUrl + 'dhlogo.png'" mode="widthFix" />

		<p class="submitTypeClass flexR-FS-C">{{submitType ? '密码登录' : '短信登录'}}</p>

		<u--form :model="formData" :rules="rules" ref="myRegisterForm">
			<u-form-item label="手机号" prop="phone" labelWidth="80" borderBottom>
				<u-input v-model="formData.phone" placeholder="输入手机号" border="none">
					<template slot="suffix">
						<u-button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" plain="true" text="获取手机号"
							type="success"></u-button>
					</template>
				</u-input>
			</u-form-item>

			<u-form-item label="密码" prop="password" labelWidth="80" borderBottom>
				<u-input v-model="formData.password" placeholder="输入密码" border="none">
					<template slot="suffix">
						<span>忘记密码？</span>
					</template>
				</u-input>
			</u-form-item>

			<!-- <u-form-item label="姓名" labelWidth="80" prop="userName" borderBottom>
				<u--input v-model="formData.userName" placeholder="输入账号" border="none"></u--input>
			</u-form-item> -->
		</u--form>

		<view class="submitBtn flexR-Cen" @click="submit">登录</view>

		<div class="flexR-FS-C mt40">
			<checkbox-group>
				<label>
					<checkbox value="cb" checked="true" color="#3c9cff" style="transform:scale(0.7)" />
				</label>
			</checkbox-group>
			<view class="ft26">若手机号未注册则自动注册，勾选即代表您已阅读并同意 <text style="color: #3c9cff;">《隐私政策》</text></view>
		</div>
	</view>
</template>

<script>
	import {
		getProjectsApi,
		addUserApi
	} from "@/api/user";
	import {
		loginImg
	} from "@/api/login";
	import WXBizDataCrypt from "@/utils/WXBizDataCrypt.js"
	import config from '@/configs/index.js'

	export default {
		data() {
			return {
				imagesYqgjUrl: config.IMAGES_URL_YQGJ,
				submitType: true,

				formData: {
					// 普通用户
					// name: "",
					phone: "",
					password: "",
				},
				rules: {
					/* 'name': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					}, */
					'phone': [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '请输入正确的手机号',
							trigger: ['change', 'blur'],
						}
					],
					'password': [{
							type: 'string',
							required: true,
							message: "请填写密码",
							trigger: ['blur', "change"],
						},
						{
							pattern: /^(?=.*[0-9])(?=.*[a-zA-z])(?=.*[?.!@#$%^&*])/g,
							message: "密码必须包含字母数字特殊字符",
							trigger: ['blur', 'change']
						},
					],
					/* 'wordVCode': {
						type: 'string',
						required: true,
						message: '请填写验证码',
						trigger: ['blur', 'change']
					}, */
				},
				session_key: "",
			}
		},
		onLoad(query) {
			this.getProjects()
		},

		mounted() {
			const userToOpenidData = uni.getStorageSync("userToOpenidData")
			this.formData.miniOpenid = userToOpenidData.openid

			uni.login({
				"provider": 'weixin',
				"onlyAuthorize": true, // 微信登录仅请求授权认证
				success: res => {
					uni.request({
						url: 'https://api.weixin.qq.com/sns/jscode2session', // 请求微信服务器
						method: 'GET',
						data: {
							appid: config.appId, //你的小程序的APPID
							secret: userToOpenidData.miniappsecret, //你的小程序秘钥secret,
							js_code: res.code, //uni.login 登录成功后的code
							grant_type: 'authorization_code' //此处为固定值
						},
						success: (res2) => {
							this.session_key = res2.data.session_key
						}
					});
				}
			});
		},

		methods: {
			async getProjects() {
				const {
					data
				} = await getProjectsApi()
				this.projectColumns = data
			},

			// 选择故障类型
			selectTypeTxtClick(item) {
				this.formData.code = item.value;
				this.formData.typeTxt = item.text;
				this.showProjectPicker = false;
			},

			// 获取手机号
			getPhoneNumber(res) {
				let pc = new WXBizDataCrypt(this.appid, this.session_key);
				let data = pc.decryptData(res.detail.encryptedData, res.detail.iv);
				if (data.phoneNumber != '') {
					this.formData.phone = data.phoneNumber
					this.$forceUpdate()
				}
			},
			confirmProject(data, value, label) {
				this.formData.projectCode = value;
			},

			submit() {
				this.$refs.myRegisterForm.validate().then((res) => {
					const params = this.removeEmptyFields(this.formData)

					addUserApi(params).then(res => {
						if (res && res.data) {
							uni.setStorageSync("RONIN-TOKEN", res.data)
							uni.showToast({
								title: '注册成功'
							});

							setTimeout(() => {
								uni.reLaunch({
									url: "/pages/initUser/initUser"
								})
							}, 500)
						}
					})
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},

			/**
			 * 剔除对象中值为空字符串的字段
			 * @param {Object} obj - 输入的对象
			 * @returns {Object} - 剔除空内容后的对象
			 */
			removeEmptyFields(obj) {
				const cleanedObj = {};

				Object.keys(obj).forEach(key => {
					if (obj[key] !== "") {
						cleanedObj[key] = obj[key];
					}
				});

				return cleanedObj;
			}
		}
	}
</script>

<style scoped lang="less">
	.register_content {
		padding: 20rpx;
		height: 100%;
		background: linear-gradient(to bottom, #f6f7fb, #eef2f5);
		box-sizing: border-box;

		.logoIcon {
			width: 200rpx;
			height: 200rpx;
			margin-top: 150rpx;
		}

		.submitTypeClass {
			width: 100%;
			font-size: 32rpx;
			font-weight: 600;
			margin: 30rpx 0;
			letter-spacing: 2rpx;
		}

		.submitBtn {
			width: 100%;
			height: 80rpx;
			margin-top: 60rpx;
			border-radius: 80rpx;
			color: #ffffff;
			background-color: #1989fa;
		}

		.btn-img {
			width: 280rpx;
			height: 80rpx;
		}

		.houtaiText {
			width: 100%;
			position: fixed;
			bottom: 40rpx;
			cursor: pointer;
			color: #3c9cff;
			font-size: 30rpx;
		}
	}

	// f6f7fb eef2f5
</style>

<style lang="less">
	.register_content {
		.u-form-item__body__left__content__label {
			font-size: 28rpx !important;
		}
	}
</style>